package com.umakr.ax.common.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Maps;
import com.umakr.ax.common.mapper.InteractiveLotteryMapper;
import com.umakr.ax.common.mapper.LotteryResultMapper;
import com.umakr.ax.common.mapper.UserDetailsMapper;
import com.umakr.ax.common.model.LotteryResult;
import com.umakr.ax.common.model.Msg;
import com.umakr.ax.common.vo.InteractiveLotteryVO;
import com.umakr.ax.core.base.BaseService;
import com.umakr.ax.utils.WebUtil;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * Created by umakr on 2018/5/5.
 * @author zj
 */
@Service
public class LotteryResultService extends BaseService<LotteryResultMapper, LotteryResult> {
    @Autowired
    MsgService msgService;

    @Autowired
    UserDetailsMapper userDetailsMapper;

    @Autowired
    InteractiveLotteryMapper interactiveLotteryMapper;

    @Value("${native.resource.path}")
    public String localUrl;

    @Value("${oss.img.path}")
    public String aliUrl;

    private static final String LOTTERY_ID= "lottery_id";
    private static final String TOTAL_PEOPLE= "totalPeople";
    private static final String MSG_ATTACHMENT_ADDR= "msgAttachmentAddr";

    public Object listAndSaveLotteryResult(Long rsId,Long drawUserId,Long lotteryId,Date startTime,Date endTime,
                                           Integer peopleCount,String keyWord,Integer status, Integer messageFrom) {
        /**
         * 由于查询数据为随机，添加status参数，用来区分抽奖操作（查询并保存）或分页操作;
         * status 0  抽奖操作（查询并保存）
         * status 1 仅分页显示查询保存后的数据
         */
        Page<LotteryResult> userPage ;
        InteractiveLotteryVO interactiveLotteryVO = new InteractiveLotteryVO();
        interactiveLotteryVO.setRsId(rsId);
        interactiveLotteryVO.setDrawUserId(drawUserId);
        interactiveLotteryVO.setStartTime(startTime);
        interactiveLotteryVO.setEndTime(endTime);
        interactiveLotteryVO.setPeopleCount(peopleCount);
        interactiveLotteryVO.setMessageFrom(messageFrom);
        if(keyWord == null || keyWord == ""){
            interactiveLotteryVO.setKeyWord1(null);
        } else {
            String[] keyWords = keyWord.split(",");
            int keyWordslength = 2;
            if(keyWords.length == 1) {
                interactiveLotteryVO.setKeyWord1(keyWords[0]);
            } else if (keyWords.length == keyWordslength) {
                interactiveLotteryVO.setKeyWord1(keyWords[0]);
                interactiveLotteryVO.setKeyWord2(keyWords[1]);
            } else {
                interactiveLotteryVO.setKeyWord1(keyWords[0]);
                interactiveLotteryVO.setKeyWord2(keyWords[1]);
                interactiveLotteryVO.setKeyWord3(keyWords[2]);
            }
        }
        Integer totalPeople = baseMapper.totalPeople(interactiveLotteryVO);
        interactiveLotteryVO.setTotalPeople(totalPeople);
        if(status == 0){
            interactiveLotteryMapper.updateLotteryStatusById(lotteryId,totalPeople);
            userPage = queryAndSaveLotteryResult(lotteryId,drawUserId,
                    interactiveLotteryVO,totalPeople);
        } else {
            userPage = queryPageList(lotteryId,totalPeople);
        }

        return userPage;
    }

    public Page<LotteryResult> queryAndSaveLotteryResult(Long lotteryId,Long drawUserId,
            InteractiveLotteryVO interactiveLotteryVO ,Integer totalPeople) {
        Date date = new Date();
        List<Map<Object,String>> userIdList;
        List<LotteryResult> listData = new ArrayList<>();
        List<LotteryResult> showdata = new ArrayList<>();
        LotteryResult userInfo = userDetailsMapper.queryUserMessageById(drawUserId);
        String drawUserName = userInfo.getNickname();
        interactiveLotteryMapper.updataDrawInfoById(lotteryId,drawUserId,date,drawUserName);
        baseMapper.deleteByLotteryId(lotteryId);
        userIdList = baseMapper.listGroupByUserId(interactiveLotteryVO);
        for (Map<Object, String> m : userIdList){
            Long userId = Long.valueOf(m.get("user_id"));
            String msgId =m.get("id");
            String[] msgIds = msgId.split(",");
            double a = Math.floor(Math.random()*msgIds.length);
            if(userId == -1) {
                Msg resultMsg = msgService.selectById(Long.parseLong(msgIds[(int) a]));
                if(resultMsg.getWechatUserData() != ""){
                    JSONObject json = JSONObject.parseObject(resultMsg.getWechatUserData());
                    listData = baseMapper.queryLotteryInfo(Long.parseLong(msgIds[(int) a]));
                    for(LotteryResult lotteryResult : listData){
                        lotteryResult.setHeadimgurl(json.get("headimgurl") == null ? "" :  json.getString("headimgurl"));
                        lotteryResult.setNickname(json.get("nickname") == null ? "" :  json.getString("nickname"));
                    }
                }
            } else {
                listData = baseMapper.queryLotteryInfoByUserId(Long.parseLong(msgIds[(int) a]),userId);
            }
            showdata.addAll(listData);
        }
        for (LotteryResult lotteryResult : showdata) {
              lotteryResult.setLotteryId(lotteryId);
              lotteryResult.setWinTime(date);
              lotteryResult.setMsgId(lotteryResult.getId());
              baseMapper.saveLotteryResult(lotteryResult);
        }
        EntityWrapper<LotteryResult> en = new EntityWrapper<>();
        if(lotteryId != null && !"".equals(lotteryId)) {
            en.eq(LOTTERY_ID, lotteryId);
            en.orderBy("msg_time",true);
        }
        Page<LotteryResult> userPage =  selectPage(WebUtil.getPage(),en);
        for (LotteryResult userList : userPage.getRecords()) {
            if(userList.getMsgContentType() == 1 || userList.getMsgContentType() ==2){
                if(userList.getMsgContentType() == 1){
                    userList.setMsgAttachmentAddr(localUrl+userList.getMsgAttachmentAddr());
                }else {
                    userList.setMsgAttachmentAddr(aliUrl+userList.getMsgAttachmentAddr());
                }
            }
        }
        WebUtil.addParamToPage(userPage,TOTAL_PEOPLE,totalPeople);
        return userPage;
    }

    public Page<LotteryResult> queryPageList(Long lotteryId,Integer totalPeople) {
        EntityWrapper<LotteryResult> en = new EntityWrapper<>();
        if(lotteryId != null && !"".equals(lotteryId)) {
            en.eq(LOTTERY_ID, lotteryId);
            en.orderBy("msg_time",true);
        }
        Page<LotteryResult> userPage =  selectPage(WebUtil.getPage(),en);
        for (LotteryResult lotteryResult : userPage.getRecords()) {
            if (lotteryResult.getMsgContentType() == 1 || lotteryResult.getMsgContentType() == 2) {
                if (lotteryResult.getMsgContentType() == 1) {
                    lotteryResult.setMsgAttachmentAddr(localUrl + lotteryResult.getMsgAttachmentAddr());
                } else {
                    lotteryResult.setMsgAttachmentAddr(aliUrl + lotteryResult.getMsgAttachmentAddr());
                }
            }
        }
        WebUtil.addParamToPage(userPage,TOTAL_PEOPLE,totalPeople);
        return userPage;
    }

    public Object listLotteryResultById(Long lotteryId,Integer totalPeople) {
        Page<Map<String,Object>> lotteryResult = baseMapper.listLotteryResultById(lotteryId);
        for(Map<String,Object> map : lotteryResult.getRecords()){
            Object msgContentType = map.get("msgContentType");
            if ((Integer.parseInt(msgContentType.toString())) ==  1 || (Integer.parseInt(msgContentType.toString())) == 2) {
                if ((Integer.parseInt(msgContentType.toString())) ==  1) {
                    map.put(MSG_ATTACHMENT_ADDR,localUrl+map.get(MSG_ATTACHMENT_ADDR));
                } else {
                    map.put(MSG_ATTACHMENT_ADDR,aliUrl+map.get(MSG_ATTACHMENT_ADDR));
                }
            }
        }
        WebUtil.addParamToPage(lotteryResult,TOTAL_PEOPLE,totalPeople);
        return lotteryResult;
    }

    public Object saveLotteryResult(Long lotteryId, long[] msgId) {
        int errorCode = 0 ;
        String msg ;
        Map<String,Object> data = Maps.newLinkedHashMap();
        Date date = new Date();
        for(Long id :msgId){
            Msg resultMsg = msgService.selectById(id);
            Long userId = resultMsg.getUserId();
            LotteryResult lr = userDetailsMapper.queryUserMessageById(userId);
            lr.setLotteryId(lotteryId);
            lr.setMessageFrom(resultMsg.getMessageFrom());
            lr.setWinTime(date);
            lr.setMsgAttachmentAddr(resultMsg.getMsgAttachmentAddr());
            lr.setMsgContentType(resultMsg.getMsgContentType());
            lr.setMsgTime(resultMsg.getMsgTime());
            lr.setMsgId(resultMsg.getId());
            lr.setMsgTxtContent(resultMsg.getMsgTxtContent());
            lr.setUserId(resultMsg.getUserId());
            baseMapper.saveLotteryResult(lr);
        }
        errorCode = 1 ;
        msg = "操作成功";
        data.put("result",1);
        return resultMap(errorCode,msg);
    }

    public Object queryByLotteryId(Long lotteryId) {
        EntityWrapper<LotteryResult> ew = new EntityWrapper<>();
        if(lotteryId != null && !"".equals(lotteryId)) {
            ew.eq(LOTTERY_ID, lotteryId);
        }
        ew.orderBy("msgTime");
        return selectPage(WebUtil.getPage(),ew);
    }

    public Object informWinUser(String id,Long lotteryId,Integer informStatus) {
        Map<String,Object> data = Maps.newLinkedHashMap();
        JSONArray json = JSONArray.fromObject(id);
        int errorCode = 0 ;
        String msg ;
        for(Object obj:json){
            long l = Long.parseLong(String.valueOf(obj));
            baseMapper.updateInformStatusById(l);
        }
        EntityWrapper<LotteryResult> ew = new EntityWrapper<>();
        ew.eq(LOTTERY_ID,lotteryId);
        ew.eq("inform_status",0);
        Integer count = baseMapper.selectCount(ew);
        //返回是否全部通知状态：allInformStatus：0未全部通知 1全部通知
        Integer allInformStatus = 0;
        if(count > 0) {
            interactiveLotteryMapper.updataInformStatus(lotteryId,1);
        } else {
            allInformStatus = 1;
            interactiveLotteryMapper.updataInformStatus(lotteryId,2);
        }

        errorCode = 1 ;
        msg = "操作成功";
        data.put("allInformStatus",allInformStatus);
        return resultMap(data,errorCode,msg);
    }
}
